import java.util.Queue;
import java.util.Scanner;

/**
 * @Title: 走迷宫
 * @Author 贾金博
 * @Package PACKAGE_NAME
 * @Date 2024/3/14 20:13
 * @description:
 */
public class 走迷宫 {
    public static Scanner sc = new Scanner(System.in);
    public static int[][] a = new int[110][110];
    public static ty[] q = new ty[10010]; // 队列
    public static int[][] ret = new int[110][110];
    public static boolean[][] st = new boolean[110][110];
    public static int[][] dir = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
    public static int n;
    public static int m;
    public static int out = 0;
    public static int in = 0;

    public static void main(String[] args) {
        n = sc.nextInt();
        m = sc.nextInt();

        for(int i = 1; i <= n; ++ i ) {
            for(int j = 1; j <= m; ++ j ) {
                a[i][j] = sc.nextInt();
                ret[i][j] = Integer.MAX_VALUE;
            }
        }

        //典型的bfs的模板
        //还是自己的数组去模拟队列吧
        ret[1][1] = 0;
        q[++ in ] = new ty(1, 1);
        while(out < in) { //不为空
//            System.out.println("!!!!");
            int x = q[++ out ].getX();
            int y = q[out].getY();

            for(int i = 0; i < 4; ++ i ) {
                int dx = x + dir[i][0];
                int dy = y + dir[i][1];
                if(check(dx, dy) && ret[dx][dy] > ret[x][y] + 1) {
                    q[++ in ] = new ty(dx, dy);
                    ret[dx][dy] = ret[x][y] + 1;
                }
            }
        }
        System.out.println(ret[n][m]);
    }

    public static boolean check(int x, int y) {
        return x >= 1 && x <= n && y >= 1 && y <= m && a[x][y] == 0;
    }
}

class ty {
    private int x;
    private int y;

    public ty() {
    }

    public ty(int x, int y) {
        this.x = x;
        this.y = y;
    }

    /**
     * 获取
     * @return x
     */
    public int getX() {
        return x;
    }

    /**
     * 设置
     * @param x
     */
    public void setX(int x) {
        this.x = x;
    }

    /**
     * 获取
     * @return y
     */
    public int getY() {
        return y;
    }

    /**
     * 设置
     * @param y
     */
    public void setY(int y) {
        this.y = y;
    }

    public String toString() {
        return "ty{x = " + x + ", y = " + y + "}";
    }
}
